'use strict';

/**
 * @ngdoc function
 * @name htmsMobileApp.controller:QiyeyinhuanbyidCtrl
 * @description
 * # QiyeyinhuanbyidCtrl
 * Controller of the htmsMobileApp
 */
angular.module('htmsMobileApp').value("qiyeYinhuanlistxConfig",{
  template: "views/tpl/qiye/yinhuan/list-tpl.html",
  searchBarTemplate: "views/tpl/qiye/yinhuan/search-bar-tpl.html",
  itemsTemplate: "views/tpl/qiye/yinhuan/items-tpl.html",
  itemTemplate: "views/tpl/qiye/yinhuan/item-tpl.html"
})
  .controller('QiyeyinhuanbyidCtrl', function($scope,$http,$location,$templateCache,Authentication,qiyeYinhuanlistxConfig,urlObj2Str,CustomHttp) {
    //一般隐患和重大隐患标识,默认为一般隐患:1,重大隐患:2
    $scope.flag = 1;
    //设置初始查询的url
    $scope.yhUrl = {
      apiUrl : "/api/yinhuan/list",
      page:1,
      pageSize:5,
      sortType:"id",
      search : [{
        key:"search_EQ_entBaseInfo.qyid",
        value:Authentication.getUser().depid
      },{
        key: "search_EQ_yhfj",
        value: 0
      }]
    };

    //报平安
    $scope.baoPinan = function(){
      var saveReportSafe = function(){
        CustomHttp.get("/api/yinhuan/reportSafe/"+Authentication.getUser().id).success(function(data){
          alert("报平安成功！");
        })
      };
      var qyid = Authentication.getUser().depid;
      CustomHttp.get("/api/yinhuan/isExistHdReport/"+qyid).success(function(data){
        if(data){
          alert("对不起！你已经上报了隐患，不能再报平安了");
        }else{
          CustomHttp.get("/api/yinhuan/isExistHdNoReport/"+qyid).success(function(data){
            if(data){
              if(confirm("本月贵企业存在已填写但未上报的隐患信息，是否继续报平安？")){
                saveReportSafe();
              }
            }else{
              saveReportSafe();
            }
          })
        }
      })
    };
    $scope.toAddYinhuan = function(){
      $location.path('/addYinhuan/'+Authentication.getUser().depid);
    };
    //查询
    $scope.queryYinhuan = function(){
      var addQymcQuery = function(uo){
        if($scope.q.val) {
          if($scope.flag == 1){
            uo.search.push({
              key: "search_LIKE_yhms",
              value: $scope.q.val
            })
          }else {
            uo.search.push({
              key: "search_LIKE_hiddenDdangerRec.yhms",
              value: $scope.q.val
            })
          }
        }
      }
      angular.element('#loadingAjaxYihuan').removeAttr("style");
      $scope.$parent.items = null;
      var uo = {
        apiUrl : "/api/yinhuan/list",
        page:1,
        pageSize:5,
        sortType:"id",
        search : [{
          key:"search_EQ_entBaseInfo.qyid",
          value:Authentication.getUser().depid
        }]
      };
      if($scope.searchActionItemSelected){
        switch ($scope.searchActionItemSelected.item){
          case "企业名称":  addQymcQuery(uo);break;
          case "一般隐患": uo.apiUrl = "/api/yinhuan/list";
            uo.sortType="scsj";$scope.flag = 1;uo.search = [{
            key:"search_EQ_entBaseInfo.qyid",
            value:Authentication.getUser().depid
          },{
            key: "search_EQ_yhfj",
            value: 0
          }];addQymcQuery(uo);break;
          case "重大隐患": uo.apiUrl = "/api/yinhuan/big/list";
            uo.sortType="id";$scope.flag = 2;uo.search = [{
            key:"search_EQ_hiddenDdangerRec.entBaseInfo.qyid",
            value:Authentication.getUser().depid
          },{
            key: "search_EQ_hiddenDdangerRec.yhfj",
            value: 1
          }]; addQymcQuery(uo);break;
          default : console.log("查询条件都不匹配");
        }
      }
      var u = urlObj2Str.getUrlStr(uo);
      CustomHttp.get(u).success(function (data) {
        $scope.$parent.items = data.content;
        $scope.$parent.first = data.first;
        $scope.$parent.last = data.last;
        $scope.$parent.uo = uo;
        //去掉加载中的进度条
        angular.element('#loadingAjaxYihuan').css("display","none");
      })

    };
    //下一页
    $scope.nextPage = function (){
      console.log(0);
      var uo;
      if($scope.uo)
        uo = $scope.uo;
      else uo = $scope.yhUrl;
      $scope.items = null;
      angular.element('#loadingAjaxYihuan').removeAttr("style");
      uo.page ++;
      var u = urlObj2Str.getUrlStr(uo);
      CustomHttp.get(u).success(function (data) {
        $scope.items = data.content;
        $scope.first = data.first;
        $scope.last = data.last;
        $scope.uo = uo;
        //去掉加载中的进度条
        angular.element('#loadingAjaxYihuan').css("display","none");
      })
    };
    //上一页
    $scope.prePage = function (){
      var uo;
      if($scope.uo)
        uo = $scope.uo;
      else uo = $scope.yhUrl;
      $scope.items = null;
      angular.element('#loadingAjaxYihuan').removeAttr("style");
      uo.page --;
      var u = urlObj2Str.getUrlStr(uo);
      CustomHttp.get(u).success(function (data) {
        $scope.items = data.content;
        $scope.first = data.first;
        $scope.last = data.last;
        $scope.uo = uo;
        //去掉加载中的进度条
        angular.element('#loadingAjaxYihuan').css("display","none");
      })
    };


    //查询过滤方式
    $scope.searchActionItems = [ '一般隐患','重大隐患','未上报'];
    $scope.searchActionItemSelected = {item : $scope.searchActionItems[0]};
    //触发查询过滤方式
    $scope.doSearch = function(searchActionItem){
      if(searchActionItem=='自定义'){
        var modalInstance = $modal.open({
          //给一个modal框的模板，根据名字获取
          templateUrl: 'myModalContent.html',
          //使用当前的控制器
          controller: 'QiyeyinhuanbyidCtrl',
          //给modal框写入一些值
          resolve: {
            searchActionItems: function () {
              return $scope.searchActionItems;
            }
          }
        });

      }
      $scope.searchActionItemSelected = {item : searchActionItem};
    };
    //以下是对列表指令的操作
    $scope.searchBarTemplate = qiyeYinhuanlistxConfig.searchBarTemplate;
    $scope.itemsTemplate = qiyeYinhuanlistxConfig.itemsTemplate;
    $scope.itemTemplate = qiyeYinhuanlistxConfig.itemTemplate;
    $scope.itemTpl = false;
    $scope.q = {val: ""};
    $scope.isSelected = function (item) {
      if (item.selected) {
        return "active"
      }
    };
    $scope.selectItem = function (item) {
      var curItem, _i, _len, _ref;
      _ref = $scope.ngModel;
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        curItem = _ref[_i];
        if (curItem.selected) {
          delete curItem.selected
        }
      }
      item.selected = true;
      return $scope.onSelect({item: item})
    };
    this.setItemTemplate = function (tpl, src) {
      $scope.itemTpl = true;
      if (src) {
        $scope.itemTemplate = src
      }
      return $templateCache.put("listxItemTpl", tpl)
    };

  })
  .controller('AddYinhuanCtrl',function($scope,$location,$routeParams,$upload,CustomHttp,RouteFilter,urlObj2Str,Authentication,serverAddr){
    CustomHttp.get("/api/entProAddress/findByQyid/"+$routeParams.qyid).success(function(data){
      $scope.jycds = data;
    });
    $scope.yhfxfses = [{key:"自查发现",value:0},{key:"监督检查",value:1},{key:"投诉举报",value:2}];
    $scope.yhlys = [{key:"自有隐患",value:0},{key:"外来隐患",value:1}];
    $scope.zgfss = [{key:"企业自主整改",value:0},{key:"强制整改",value:1}];
    $scope.zglxs = [{key:"立即整改",value:0},{key:"限期整改",value:1},{key:"停业停产整改",value:2}];
    $scope.zgzts = [{key:"未整改",value:1},{key:"已整改",value:2},{key:"整改中",value:3}];
    //d1 第一步填写隐患类别，d2 第二步填写隐患详情，d3 第三步填写隐患整改情况
    $scope.d = "d1";
    //查询隐患类别（自查标准）
    $scope.searchZcbz= function(){
      angular.element('#loadingAjaxZcbz').removeAttr("style");
      var uo = {
        apiUrl : "/api/zcbzlb/list",
        page:1,
        pageSize:10,
        sortType:"zcbzlbid",
        search:[{
          key : "search_EQ_sfyx",//是否有效，1有效，0无效
          value : "1"
        }]
      };
      if($scope.q.zcbz){
        uo.search.push({
          key : "search_LIKE_zcbzjtms",
          value : $scope.q.zcbz
        });
        CustomHttp.get(urlObj2Str.getUrlStr(uo)).success(function(data){
            $scope.zcbzs = data;
          $scope.uo = uo;
          //去掉加载中的进度条
          angular.element('#loadingAjaxZcbz').css("display","none");
        }).error(function(error){
          console.error(error);
        });
      }
    };
    $scope.doPage = function(type){
      if($scope.zcbzs) {
        if (type === "next") {
          $scope.zcbzs = null;
          $scope.uo.page++;
          CustomHttp.get(urlObj2Str.getUrlStr($scope.uo)).success(function (data) {
            $scope.zcbzs = data;
          })
        }
        if (type === "pre") {
          $scope.zcbzs = null;
          $scope.uo.page--;
          CustomHttp.get(urlObj2Str.getUrlStr($scope.uo)).success(function (data) {
            $scope.zcbzs = data;
          })
        }
      }
    };
    var match = function(zgwcrq){
      return /\d{4}-\d{2}-\d{2}/.test(zgwcrq);
    };
    $scope.canAccess = function(filterValue){
      return RouteFilter.canAccess(filterValue);
    };
    $scope.mathZgwcrq = function(zgwcrq){
      if(zgwcrq ==null ||zgwcrq=="--" || zgwcrq.length ==0 || zgwcrq == "undefined" || zgwcrq==""){
        return true;
      }else
      return match(zgwcrq);
    };
    $scope.isCollapsed = true;
    //日期年数组
    var now = new Date();
    var year = now.getFullYear() + 8;
    var yearList = [];
    for(var i = 0;i <= 30;i++){
      yearList.push(year-i);
    }
    $scope.yearList = yearList;
    //跳转到填写隐患情况
    $scope.shangBaoYinhuan = function(type,zcbzid){
      $scope.d = "d2";
      $scope.type = type;
      if(type=="yiban") {
        $scope.yhModel = {
          yhfj:0,//一般隐患
          selfExaClass:{
            zcbzlbid:zcbzid
          },
          entBaseInfo:{
            qyid:$routeParams.qyid
          }
        };
      }else if(type=="zhongda"){
        $scope.yhBigModel = {};
        $scope.yhModel = {
          yhfj:1,//重大隐患
          selfExaClass:{
            zcbzlbid:zcbzid
          },
          entBaseInfo:{
            qyid:$routeParams.qyid
          }
        };
      }
    };
    //跳转到填写整改情况(如果是重大隐患则跳到填写重大隐患整改情况)
    $scope.shangBaoYinhuan2 = function(){
      if($scope.type == "zhongda"){
        $scope.d = "d4";
      }else {
        $scope.d = "d3";
      }
      $scope.yhModel.fxyhsj = $scope.fxsjnf + "-" + $scope.fxsjyf + "-"+$scope.fxsjday;
    };

    //重大隐患最后还是跳到填写一般整改情况页面，共用
    $scope.shangBaoYinhuan3 = function(){
      $scope.d = "d3";
    }

    //上传图片所用的方法
    var uploadFile = function(hdid){
      var yhfiles = $scope.yhfiles;
      var yhzgfiles = $scope.yhzgfiles;
      var fileArr = [];
      var flag;
      if(yhfiles&&yhfiles.length>0){
        flag = 0;//隐患图片
        fileArr.push(yhfiles[0]);
      }if(yhzgfiles&&yhzgfiles.length>0){
        flag = 1;//整改图片
        fileArr.push(yhzgfiles[0]);
      }
      var des;
      if(fileArr.length&&fileArr.length==2){
        des = "0,1";//两种图片都有
      }else if(fileArr.length==1){
        if(flag==0){
          des ="0";//只有隐患图片
        }else if(flag == 1){
          des = "1";//只有整改图片
        }
      }
      //开始上传图片
          $upload.upload({
            url: '/'+serverAddr.name+'/api/yinhuan/upload?hdid='+hdid + "&des=" + des,
            file: fileArr
          }).progress(function (evt) {
            var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
            console.log('progress: ' + progressPercentage + '% ' + evt.config.file.name);
          }).success(function (data, status, headers, config) {
            console.log('file ' + config.file.name + 'uploaded. Response: ' + data);
          });
    };

    //隐患上报
    $scope.shangbao = function(){
      $scope.yhModel.zgwcrq = $scope.nfzhenggai + "-" + $scope.yfzhenggai + "-"+$scope.dayzhenggai;
      if(!match($scope.yhModel.zgwcrq)){
        $scope.yhModel.zgwcrq = "";
      }
      $scope.yhModel.tbr = Authentication.getUser().name;
      $scope.yhModel.bdzt = 1;//已上报
      if($scope.type == "zhongda"){
        //重大
        $scope.yhBigModel.mbrwdqrq = $scope.mbrwdqrqY + "-" + $scope.mbrwdqrqM + "-" + $scope.mbrwdqrqD;
        $scope.yhBigModel.zgrwdqrq = $scope.zgrwdqrqY + "-" + $scope.zgrwdqrqM + "-" + $scope.zgrwdqrqD;
        $scope.yhBigModel.zlcsdqrq = $scope.zlcsdqrqY + "-" + $scope.zlcsdqrqM + "-" + $scope.zlcsdqrqD;
        $scope.yhBigModel.zgzjdqrq = $scope.zgzjdqrqY + "-" + $scope.zgzjdqrqM + "-" + $scope.zgzjdqrqD;
        $scope.yhBigModel.zgsxdqrq = $scope.zgsxdqrqY + "-" + $scope.zgsxdqrqM + "-" + $scope.zgsxdqrqD;
        $scope.yhBigModel.zgyadqrq = $scope.zgyadqrqY + "-" + $scope.zgyadqrqM + "-" + $scope.zgyadqrqD;
        $scope.yhBigModel.nrzljhrq = $scope.nrzljhrqY + "-" + $scope.nrzljhrqM + "-" + $scope.nrzljhrqD;
        if(!match($scope.yhBigModel.mbrwdqrq)){
          $scope.yhBigModel.mbrwdqrq = null;
        }
        if(!match($scope.yhBigModel.zgrwdqrq)){
          $scope.yhBigModel.zgrwdqrq = null;
        }
        if(!match($scope.yhBigModel.zlcsdqrq)){
          $scope.yhBigModel.zlcsdqrq = null;
        }
        if(!match($scope.yhBigModel.zgzjdqrq)){
          $scope.yhBigModel.zgzjdqrq = null;
        }
        if(!match($scope.yhBigModel.zgsxdqrq)){
          $scope.yhBigModel.zgsxdqrq = null;
        }
        if(!match($scope.yhBigModel.zgyadqrq)){
          $scope.yhBigModel.zgyadqrq = null;
        }
        if(!match($scope.yhBigModel.nrzljhrq)){
          $scope.yhBigModel.nrzljhrq = null;
        }
        $scope.yhBigModel.hiddenDdangerRec = $scope.yhModel;
        console.log($scope.yhBigModel);
        CustomHttp.post("/api/yinhuan/big/create",$scope.yhBigModel).success(function(data){
          uploadFile(data.hdid);
          alert("上报成功！");
          $location.path("/qiyeyinhuanByid");
        })
      }else {
        //一般
        CustomHttp.post("/api/yinhuan/create",$scope.yhModel).success(function(data){
          uploadFile(data.hdid);
          alert("上报成功！");
          $location.path("/qiyeyinhuanByid");
        })
      }

    };
    //隐患保存
    $scope.baocun = function(){
      $scope.yhModel.zgwcrq = $scope.nfzhenggai + "-" + $scope.yfzhenggai + "-"+$scope.dayzhenggai;
      if(!match($scope.yhModel.zgwcrq)){
        $scope.yhModel.zgwcrq = "";
      }
      $scope.yhModel.tbr = Authentication.getUser().name;
      $scope.yhModel.bdzt = 0;//未上报
      if($scope.type == "zhongda"){
        //重大
        $scope.yhBigModel.mbrwdqrq = $scope.mbrwdqrqY + "-" + $scope.mbrwdqrqM + "-" + $scope.mbrwdqrqD;
        $scope.yhBigModel.zgrwdqrq = $scope.zgrwdqrqY + "-" + $scope.zgrwdqrqM + "-" + $scope.zgrwdqrqD;
        $scope.yhBigModel.zlcsdqrq = $scope.zlcsdqrqY + "-" + $scope.zlcsdqrqM + "-" + $scope.zlcsdqrqD;
        $scope.yhBigModel.zgzjdqrq = $scope.zgzjdqrqY + "-" + $scope.zgzjdqrqM + "-" + $scope.zgzjdqrqD;
        $scope.yhBigModel.zgsxdqrq = $scope.zgsxdqrqY + "-" + $scope.zgsxdqrqM + "-" + $scope.zgsxdqrqD;
        $scope.yhBigModel.zgyadqrq = $scope.zgyadqrqY + "-" + $scope.zgyadqrqM + "-" + $scope.zgyadqrqD;
        $scope.yhBigModel.nrzljhrq = $scope.nrzljhrqY + "-" + $scope.nrzljhrqM + "-" + $scope.nrzljhrqD;
        if(!match($scope.yhBigModel.mbrwdqrq)){
          $scope.yhBigModel.mbrwdqrq = null;
        }
        if(!match($scope.yhBigModel.zgrwdqrq)){
          $scope.yhBigModel.zgrwdqrq = null;
        }
        if(!match($scope.yhBigModel.zlcsdqrq)){
          $scope.yhBigModel.zlcsdqrq = null;
        }
        if(!match($scope.yhBigModel.zgzjdqrq)){
          $scope.yhBigModel.zgzjdqrq = null;
        }
        if(!match($scope.yhBigModel.zgsxdqrq)){
          $scope.yhBigModel.zgsxdqrq = null;
        }
        if(!match($scope.yhBigModel.zgyadqrq)){
          $scope.yhBigModel.zgyadqrq = null;
        }
        if(!match($scope.yhBigModel.nrzljhrq)){
          $scope.yhBigModel.nrzljhrq = null;
        }
        $scope.yhBigModel.hiddenDdangerRec = $scope.yhModel;
        console.log($scope.yhBigModel);
        CustomHttp.post("/api/yinhuan/big/create", $scope.yhBigModel).success(function (data) {
          uploadFile(data.hdid);
          alert("保存成功！");
          $location.path("/qiyeyinhuanByid");
        })
      }else {
        //一般
        CustomHttp.post("/api/yinhuan/create", $scope.yhModel).success(function (data) {
          uploadFile(data.hdid);
          alert("保存成功！");
          $location.path("/qiyeyinhuanByid");
        })
      }
    };
  }).directive("qiyeYinhuanlistX", ["CustomHttp", "$templateCache", "qiyeYinhuanlistxConfig", function (CustomHttp, $templateCache, qiyeYinhuanlistxConfig) {
    return {
      restrict: "E",
      transclude: true,
      replace: true,
      require: "ngModel",
      scope: {
        title: "@",
        hideSearchBar: "@",
        itemHandlers: "&",
        //loadUrl ngModel 改成双向数据绑定
        loadUrl: "=",
        ngModel: "=",
        onSelect: "&",
        onLoad: "&"
      },
      templateUrl: function (tElement, tAttrs) {
        return qiyeYinhuanlistxConfig.template
      },
      //列表的所有操作都使用同一个控制器
      controller: "QiyeyinhuanbyidCtrl",
      link: function (scope, iElement, iAttrs, controller) {
        //初始化列表数据
        if (scope.loadUrl) {
          CustomHttp.get(scope.loadUrl).success(function (data) {
            scope.ngModel = data.content;
            //去掉加载中的进度条
            angular.element('#loadingAjaxYihuan').css("display","none");
            return scope.onLoad();
          })
        }
        $(".list-x-main div[ng-transclude]").remove();
        return $(".list-x-main").removeAttr("title")
      }
    }
  }]).directive("qiyeyinhuanitemTemplate", function () {
    return {
      restrict: "E",
      replace: true,
      transclude: true,
      require: "^qiyeYinhuanlistX",
      scope: {itemTemplate: "@"},
      template: "<div ng-transclude></div>",
      link: function (scope, iElement, iAttrs, controller) {
        return controller.setItemTemplate(iElement.html(), scope.itemsTemplate)
      }
    }
  });
